<?php

namespace App\Http\Controllers\Backend;

use App\Events\LoginLogEvent;
use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\AdminRequest;
use App\Http\Requests\Backend\EditPasswordRequest;
use App\Http\Requests\Backend\LoginRequest;
use App\Models\Admin;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
    protected $guard = 'admin';

    public function __construct()
    {
        $this->middleware(
            'backend.login.check',
            [
                'except' => [
                    'showLoginForm', 'loginHandle','logoutHandle'
                ],
            ]
        );
    }

    public function index()
    {
        //TODO::帐号恢复
        $keywords = request('keyword', '');

        $admins = Admin::when($keywords, function ($query) use ($keywords) {
            return $query->where('name', 'like', "%{$keywords}%")
                         ->orWhere('email', 'like', "%{$keywords}%");
        })->orderByDesc('id')
          ->paginate(request('page_size', 10));

        return view('backend.admin.index', compact('admins'));
    }

    public function create()
    {
        $roles = Role::where('guard_name','admin')->get();

        return view('backend.admin.create',compact('roles'));
    }

    public function store(
        AdminRequest $request,
        Admin $admin
    ) {
        $admin->fill($request->filldata())->save();
        $admin->syncRoles($request->input('role_name',[]));

        flash('管理员添加成功', 'success');

        return back();
    }

    public function edit($id)
    {
        $admin = Admin::findOrFail($id);
        $roles = Role::where('guard_name','admin')->get();

        return view('backend.admin.edit', compact( 'admin','roles'));
    }

    public function update(AdminRequest $request, $id)
    {
        $admin = Admin::findOrFail($id);

        $admin->fill($request->filldata())->save();

        $admin->syncRoles($request->input('role_name',[]));

        flash('管理员编辑成功', 'success');

        return back();
    }

    public function destroy($id)
    {
        $admin = Admin::findOrFail($id);
        if ($admin->isSuper()) {
            flash('当前用户是超级管理员账户无法删除');
        } else {
            $admin->delete();
            flash('管理员删除成功', 'success');
        }

        return back();
    }

    public function loginHandle(LoginRequest $request){
        if (! Auth::guard($this->guard)->attempt($request->only(['email', 'password'], $request->input('remember_me')))) {
            flash('邮箱或密码错误');
            //TODO::这里有个bug,密码错误的情况下,email没办法回填到登陆表单里
            //登陆日志
            event(new LoginLogEvent(Auth::guard($this->guard)->user(),'后台','失败'));
            return back()->withInput(['email']);
        }
        //登陆日志
        event(new LoginLogEvent(Auth::guard($this->guard)->user(),'后台','成功'));

        return redirect(route('backend.dashboard.index'));
    }



    public function logoutHandle()
    {
        Auth::guard($this->guard)->logout();
        flash('成功退出', 'success');

        return redirect(route('backend.login'));
    }

    public function showLoginForm(){
        if (Auth::guard($this->guard)->check()) {
            return \redirect(\route('backend.dashboard.index'));
        }
        return view('backend.auth.login');
    }

    public function showEditPasswordForm()
    {
        return view('backend.auth.edit_password');
    }

    public function editPasswordHandle(EditPasswordRequest $request)
    {
        $administrator = Auth::guard($this->guard)->user();
        if (
        ! \Hash::check(
            $request->input('old_password'),
            $administrator->password
        )
        ) {
            flash('原密码不正确');

            return back();
        }
        $administrator->fill($request->filldata())->save();
        flash('密码修改成功', 'success');

        return back();
    }

}
